// 用户相关仓库
import { defineStore } from "pinia";
import type { LoginParamsType } from "@/api/user/types";
import { reqLogin, reqUserInfo } from "@/api/user";
import { storage } from "@/utils/util.ts";
import { constRouter } from "@/router/routers";

export const useUserStore = defineStore("user", {
  state: () => {
    return {
      token: storage.getItem("token") || "",
      userInfo: {},
      menuRouter: constRouter,
    };
  },
  actions: {
    //登录逻辑
    async login(data: LoginParamsType) {
      const res: any = await reqLogin(data);
      if (res.code === 200) {
        this.token = res.data;
        // 持久化存储
        storage.setItem("token", res.data);
        // localStorage.setItem("token", res.data.token);
        // 返回成功响应
        return Promise.resolve(res);
      } else {
        // 登录失败，返回错误信息
        return Promise.reject(res.data);
      }
    },
    // 获取用户信息
    async getUserInfo() {
      const res: any = await reqUserInfo();
      console.log("res:", res);
      if (res.code === 200) {
        this.userInfo = res.data;
        return Promise.resolve(res);
      } else {
        return Promise.reject(res.message);
      }
    },
    // 退出登录
    userLogout() {
      this.token = "";
      this.userInfo = {};
      storage.removeItem("token");
    },
  },
});
